package csc.fresher.commons;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("IDCardNumberValidator")
public class IDCardNumberValidator implements Validator{

	private static final String ID_CADR_PATTERN = "^\\s*\\d+\\s*$";

	private Pattern pattern;
	private Matcher matcher;

	public IDCardNumberValidator(){
		  pattern = Pattern.compile(ID_CADR_PATTERN);
	}

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		matcher = pattern.matcher(value.toString());
		if(!matcher.matches()){

			FacesMessage msg = 
				new FacesMessage("ID Card Number validation failed.", 
						"Invalid ID Card Number format.");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);

		}

	}
}